跳到主要内容

触发器属性(PropertyTrigger)

表示一个触发器属性(trigger property),可触发事件并通知监听器。

与其他 属性(Property) 不同,Trigger 不保存持久值;调用 fire() 时仅发出事件。

字段(Fields)

addListener

注册监听器(listener),在触发器触发时调用。

此函数有两种签名:

  • addListener(callback) —— 简单形式,只需传入回调函数。
  • addListener(anchor, callback) —— 传入一个锚点对象(anchor)和回调函数。 锚点对象会与监听器一同存储,并在回调被调用时传回。这样可以防止某些你希望在监听期间保持存活的对象被垃圾回收。

重要: 如果你是通过局部变量获取 ViewModel 或属性 (例如 local vm = context:viewModel()),并在没有将该 ViewModel 存到别处的情况下添加监听器,那么函数返回后它可能会被垃圾回收。为避免这种情况,可以:

  • 将 ViewModel 保存到 self 上(例如 self.vm = context:viewModel()
  • 将 ViewModel 作为 anchor 参数传给 addListener
local vmi = context:viewModel()
if vmi then
local cannon = vmi:getTrigger('cannon')
if cannon then
cannon:addListener(function()
print("cannon fired!")
end)

cannon:fire()
end
end

使用 anchor 参数让 ViewModel 保持存活:

local vm = context:viewModel()
if vm then
local cannon = vm:getTrigger('cannon')
if cannon then
cannon:addListener(vm, function(anchor)
-- 'anchor' is the vm we passed, kept alive by the listener
print("cannon fired!")
end)
end
end

removeListener

移除之前注册的监听器。请在不再需要监听器时及时移除,以避免泄漏(leaks)。

此函数有两种签名:

  • removeListener(callback) —— 传入要移除的回调函数。
  • removeListener(anchor, callback) —— 传入 anchor 和回调函数。 出于与 addListener API 对称性的考虑,这里接受 anchor 参数,但真正用于匹配的只有回调函数。
function init(self: MyNode, context: Context): boolean
local vmi = context:viewModel()
if vmi then
local cannon = vmi:getTrigger('cannon')
if cannon then
self.cannon = cannon
self.onCannonFired = onCannonFired
cannon:addListener(onCannonFired)
end
end

return true
end

function removeCannonListener(self: MyNode)
if self.cannon then
self.cannon:removeListener(self.onCannonFired)
end
end

方法(Methods)

fire

触发该 Trigger,并通知所有已注册监听器。

local vmi = context:viewModel()
if vmi then
local cannon = vmi:getTrigger('cannon')
if cannon then
cannon:addListener(function()
print("cannon fired!")
end)

cannon:fire()
end
end